package simulation.threads;

import gui.Presentation;
import common.Constants;
import common.SimulationSettings;
import simulation.initiatives.EnginePush;

public class EnginePushThread extends EnginePush implements Runnable {
  private volatile int displayRate = Constants.DEFAULT_DISPLAY_RATE;
  private volatile boolean threadSuspended = true;

  public EnginePushThread(Presentation presentation, SimulationSettings settings) {
    super(presentation, settings);
  }
  
  public synchronized void adjustDisplayRate(int newRate) {
    displayRate = newRate;
  }
    
  public synchronized void start() {
    threadSuspended = false;
    notify();
  }
  
  public synchronized void pause() {
    threadSuspended = true;
  }
  
  public synchronized void reset() {
    super.reset();
  } 
  
  public void run() {
    Thread thisThread = Thread.currentThread();
    
    while(true) {
      try {
        if (!threadSuspended) {
          thisThread.sleep(displayRate);
          super.step();
        }
        else {
          synchronized (this) {
            wait();
          }
        }
      }
      catch (InterruptedException e) {
        e.printStackTrace();
      }      
    }
  }
}
